package com.isoft.mapper;

import com.isoft.entity.DfmeRtneEntity;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface DfmeRtneMapper {

    @Insert("INSERT INTO MSG_META(SENDER, RECEIVER, SEQUENCE_NUMBER, DATE_TIME, MSG_TYPE, SUB_TYPE) VALUES(#{entity.meta.sender}, #{entity.meta.receiver}, #{entity.meta.sequenceNumber}, TO_TIMESTAMP(#{entity.meta.dateTime}, 'YYYYMMDDHH24MISS'), #{entity.meta.type}, #{entity.meta.subType})")
    void insertMeta(@Param("entity") DfmeRtneEntity entity);

    @Insert("INSERT INTO FLIGHT_BASE(" +
            "FLIGHT_ID, FLIGHT_ATTRIBUTE, FLIGHT_FILE_ID, FLIGHT_IDENTIFIER, " +
            "STATUS, INTERNAL_STATUS, MANUAL_STATUS, MANUAL_INTERNAL_STATUS) " +
            "VALUES(" +
            "#{dflt.flightId,jdbcType=NUMERIC}, " +
            "#{dflt.flightAttribute,jdbcType=VARCHAR}, " +
            "#{dflt.flightFileId,jdbcType=VARCHAR}, " +
            "#{dflt.flightIdentifier,jdbcType=VARCHAR}, " +
            "'RETURNED', " +
            "#{dflt.internalAbnormalStatus,jdbcType=VARCHAR}, " +
            "#{dflt.manualAbnormalStatus,jdbcType=VARCHAR}, " +
            "#{dflt.manualInternalAbnormalStatus,jdbcType=VARCHAR})")
    void insertFlightBase(DfmeRtneEntity entity);

    @Update("UPDATE FLIGHT_BASE SET " +
            "STATUS = 'RETURNED', " +
            "FLIGHT_ATTRIBUTE = #{dflt.flightAttribute,jdbcType=VARCHAR}, " +
            "MANUAL_STATUS = #{dflt.manualAbnormalStatus,jdbcType=VARCHAR}, " +
            "MANUAL_INTERNAL_STATUS = #{dflt.manualInternalAbnormalStatus,jdbcType=VARCHAR} " +
            "WHERE FLIGHT_ID = #{dflt.flightId,jdbcType=NUMERIC}")
    int updateFlightBase(DfmeRtneEntity entity);

    // 最终解决方案：使用达梦数据库的 IDENTITY 列特性
    @Insert("INSERT INTO FLIGHT_IRREGULARITY(" +
            "FLIGHT_ID, ABNORMAL_STATUS, ABNORMAL_REASON, " +
            "INTERNAL_STATUS, INTERNAL_REASON, MANUAL_ABNORMAL_STATUS, " +
            "MANUAL_ABNORMAL_REASON, MANUAL_INTERNAL_STATUS, MANUAL_INTERNAL_REASON) " +
            "VALUES(" +
            "#{dflt.flightId,jdbcType=NUMERIC}, " +
            "#{dflt.abnormalStatus,jdbcType=VARCHAR}, " +
            "#{dflt.abnormalReason,jdbcType=VARCHAR}, " +
            "#{dflt.internalAbnormalStatus,jdbcType=VARCHAR}, " +
            "#{dflt.internalAbnormalReason,jdbcType=VARCHAR}, " +
            "#{dflt.manualAbnormalStatus,jdbcType=VARCHAR}, " +
            "#{dflt.manualAbnormalReason,jdbcType=VARCHAR}, " +
            "#{dflt.manualInternalAbnormalStatus,jdbcType=VARCHAR}, " +
            "#{dflt.manualInternalAbnormalReason,jdbcType=VARCHAR})")
    void insertFlightIrregularity(DfmeRtneEntity entity);

    @Select("SELECT COUNT(*) FROM FLIGHT_BASE WHERE FLIGHT_ID = #{flightId}")
    int checkFlightExists(Long flightId);
}